$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
    console.log('Data ready event triggered');
    var mstform = $NG.getCmpApi("p_form_equipment_list");
    var dgrid = $NG.getCmpApi('p_form_equipment_list_d');



    $NG.getCmpApi('toolbar_p_form_equipment_list_d').insert({
        id: "user_insert",
        text: "插行",
        iconCls: "icon-InsertRow"
    });


    {//按钮事件BEGIN
        useClick(async function ({ args }) {
            insertClick()
        }, "user_insert");
    }//按钮事件ENG

    {//初始化逻辑BEGIN
        cntMFilter();
        cntDFilter();
        if ($NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue()) {
            getPtInfoByPhid();
        };

        //页面条件
        if (page.oType == "add" || page.oType == "edit" || page.oType == "copy") {
            $NG.updateState(function (updater, state) {
                if (!mstform.getItem('u_create_org').getValue()) {
                    updater.data.p_form_equipment_list.setProps({
                        u_create_org: $NG.getUser().orgID,
                        u_create_org_EXName: $NG.getUser().orgName,
                        u_using_org: $NG.getUser().userID,
                        u_using_org_EXName: $NG.getUser().orgName,
                    });
                }
            });
        }
    }//初始化逻辑END


    {//表头字段变化逻辑BEGIN
        useValuesChange(({ args }) => {
            cntMFilter();
            getPtInfoByPhid();
        }, 'p_form_equipment_list.phid_pc');
        useValuesChange(({ args }) => {
            cntDFilter();
            getCntMInfoByPhid();
        }, 'p_form_equipment_list.u_cnt_no');
        useValuesChange(({ args }) => {
            caculatedgrid()
        }, 'p_form_equipment_list.u_win_bid_svc_amt');

    }//表头字段变化逻辑END

    useUpdateRows(({ args, table }) => {
        console.log('useUpdateRows begin')
        const rows = args[0];
        const clearList = {}; // 用于存储清单编号
        let clearCodeCounter = 1; // 清单编码计数器，从 1 开始

        rows.forEach((items) => {
            //1、自动生成设备清单
            const { u_equipment_list_name, u_model } = items;
            const key = `${u_equipment_list_name}_${u_model}`; // 根据名称和型号生成唯一标识符

            if (!clearList[key]) {// 如果清单编号不存在，则生成新的编号
                const serialPart = String(clearCodeCounter).padStart(4, '0'); // 将计数器格式化为4位
                clearList[key] = 'A' + serialPart; // 生成清单编号
                clearCodeCounter++;
            }
            items.u_equipment_list_no = clearList[key];// 将清单编号赋值到明细对象中的清单编码字段


            //根据导入的合同编码匹配合同清单
            if (!items.u_cnt_item) {
                getCntDInfoByNo(items)
            }


            //3、匹配拟分包项
            if (!items.u_sub_item && items.u_sub_no) {
                $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_sub_no + "'" }, function (res) {
                    if (res.count > 0) {
                        var data = JSON.parse(res.data)[0].extendObjects; //单返回值

                        items.u_sub_item = data.phid;
                        items.u_sub_item_EXName = data.itemno;

                        items.u_sub_item_category = data.phid_resbs;
                        items.u_sub_item_category_EXName = data.name;


                        items.u_sub_name = data.itemname
                        items.u_sub_ggxh = data.spec
                    } else {
                        console.log(items.u_sub_no + ':useUpdateRows没有找到拟分包清单')
                        items.u_u_pur_item = null;
                        items.u_u_pur_item_EXName = null;
                    }
                });
                items.u_sub_invoice_type = '8570000000000151'
                items.u_sub_invoice_type_EXName = '6%增值税专用发票'
                dgrid.refreshView()
            }

            //3、匹配拟采购项目
            if (!items.u_pur_item && items.u_pur_no) {
                $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_pur_no + "'" }, function (res) {
                    if (res.count > 0) {
                        var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值

                        items.u_pur_item_category = purdata.phid_resbs;
                        items.u_pur_item_category_EXName = purdata.name;

                        items.u_pur_item = purdata.phid;
                        items.u_pur_item_EXName = purdata.itemno;



                        items.u_pur_name = purdata.itemname
                        items.u_pur_ggxh = purdata.spec
                    } else {
                        console.log('useUpdateRows没有找到拟采购清单')
                        items.u_u_pur_item = null;
                        items.u_u_pur_item_EXName = null;
                    }
                });
                items.u_pur_invoice_type = '8570000000000154'
                items.u_pur_invoice_type_EXName = '13%增值税专用发票'
                dgrid.refreshView()
            }


            //4、匹配自制项目
            if (!items.u_self_item && items.u_self_no) {
                $NG.execServer("getItemdataByNo", { itemno: "'" + items.u_self_no + "'" }, function (res) {
                    if (res.count > 0) {
                        var selfdata = JSON.parse(res.data)[0].extendObjects; //单返回值

                        items.u_self_item = selfdata.phid;
                        items.u_self_item_EXName = selfdata.itemno;


                        items.u_self_name = selfdata.itemname
                        items.u_self_ggxh = selfdata.spec
                    } else {
                        console.log('useUpdateRows没有找到拟自制清单')
                        items.u_self_item = null;
                        items.u_self_item_EXName = null;

                    }
                    dgrid.refreshView()
                });
            }
        });
        console.log('useUpdateRows end')
    }, "p_form_equipment_list_d");

    useUpdateRow(({ args, table }) => {
        console.log('useUpdateRow begin')
        const record = args[0];

        //2. 更新拟分包项
        if (record.u_sub_item) {
            $NG.execServer("getItemdataByPhid", { phid: record.u_sub_item }, function (res) {
                if (res.count > 0) {
                    var data = JSON.parse(res.data)[0].extendObjects; //单返回值

                    record.u_sub_item_category = data.phid_resbs;
                    record.u_sub_item_category_EXName = data.name;
                    record.u_sub_name = data.itemname
                    record.u_sub_ggxh = data.spec

                } else {
                    // console.log('没有找到拟分包清单')
                    // record.u_u_sub_item = null;
                    // record.u_u_sub_item_EXName = null;
                    // record.u_sub_ggxh = null;
                }
                dgrid.refreshView()
            });
        }


        //3. 更新拟采购项
        if (record.u_pur_item) {
            $NG.execServer("getItemdataByPhid", { phid: record.u_pur_item }, function (res) {
                if (res.count > 0) {
                    var purdata = JSON.parse(res.data)[0].extendObjects; //单返回值

                    record.u_pur_item_category = purdata.phid_resbs;
                    record.u_pur_item_category_EXName = purdata.name;
                    record.u_pur_name = purdata.itemname;
                    record.u_pur_ggxh = purdata.spec
                } else {
                    // console.log('没有找到拟采购清单')
                    // record.u_u_pur_item = null;
                    // record.u_u_pur_item_EXName = null;
                }
                dgrid.refreshView()
            });
        }


        //4. 更新拟自制项
        if (record.u_self_item) {
            $NG.execServer("getItemdataByPhid", { phid: record.u_self_item }, function (res) {
                if (res.count > 0) {
                    var data = JSON.parse(res.data)[0].extendObjects; //单返回值

                    record.u_self_item_category = data.phid_resbs;
                    record.u_self_item_category_EXName = data.name;
                    record.u_self_name = data.itemname;
                    record.u_self_ggxh = data.spec
                } else {
                    // console.log('没有找到拟采购清单')
                    // record.u_u_pur_item = null;
                    // record.u_u_pur_item_EXName = null;
                }
                dgrid.refreshView()
            });
        }

        //选择清单名称带出一些数据
        if(record.u_cnt_item){
            
        }
        console.log('useUpdateRow end')
    }, "p_form_equipment_list_d");


    {//表体订阅字段更新逻辑BEGIN
        // 统一的更新逻辑函数
        const updateCosts = (args) => {
            // 未税单价   = 含税单价/1+税率
            args[0].u_sub_prc = ((args[0].u_sub_prc_vat || 0) / (1 + (args[0].u_sub_tax_rate || 0)));
            // 含税成本 = 数量 * 含税单价
            args[0].u_sub_cost_vat = (args[0].u_qty || 0) * (args[0].u_sub_prc_vat || 0);
            // 成本未税 = 数量 * 含税单价 / 1+税率
            args[0].u_sub_cost = (args[0].u_qty || 0) * (args[0].u_sub_prc_vat || 0) / (1 + (args[0].u_sub_tax_rate || 0));

            // 采购
            args[0].u_pur_prc = (args[0].u_pur_prc_vat || 0) / (1+args[0].u_pur_tax_rate || 0) 
            args[0].u_pur_cost_vat = (args[0].u_qty || 0) * (args[0].u_pur_prc_vat || 0);
            args[0].u_pur_cost = (args[0].u_qty || 0) * (args[0].u_pur_prc_vat || 0) / (1 + (args[0].u_pur_tax_rate || 0));

            // 自制
            args[0].u_self_prc = (args[0].u_self_prc_vat || 0) * (1+args[0].u_self_tax_rate || 0);
            args[0].u_self_cost_vat = (args[0].u_qty || 0) * (args[0].u_self_prc_vat || 0) ;
            args[0].u_self_cost = (args[0].u_qty || 0) * (args[0].u_self_prc_vat || 0) / (1 + (args[0].u_self_tax_rate || 0));
        };

        // 用于绑定触发字段和更新的通用函数
        const createChangeHandler = (fields) => {
            fields.forEach((field) => {
                useDataIndexChange(({ args, instance }) => {
                    updateCosts(args);
                    instance.updateRow(args[0]);
                }, field);
            });
        };

        // 绑定字段变化以触发更新
        createChangeHandler([
            'p_form_equipment_list_d.u_qty',
            'p_form_equipment_list_d.u_sub_prc_vat',
            'p_form_equipment_list_d.u_sub_tax_rate',
            'p_form_equipment_list_d.u_pur_prc_vat',
            'p_form_equipment_list_d.u_pur_tax_rate',
            'p_form_equipment_list_d.u_self_prc_vat',
            'p_form_equipment_list_d.u_self_tax_rate',
        ]);
        useDataIndexChange(({ args, instance }) => {
            const record = args[0];
            if (record.u_cnt_item) {
                getCntDInfoByPhid(record);
            }
        }, "u_cnt_item");


    }//表体订阅字段更新逻辑END

    {//表体字段汇总逻辑BEGIN
        useUpdateRows(({ args }) => {
            const rows = args[0];
            caculatedgrid()
        }, "p_form_equipment_list_d");

        useUpdateRows(({ args }) => {
            const rows = args[0];
            caculatedgrid()
        }, "p_form_equipment_list_impl");

        useUpdateRows(({ args }) => {
            const rows = args[0];
            caculatedgrid()
        }, "p_form_equipment_list_svc");
    }//表体字段汇总逻辑END



    //自动获取设备清单的实施费用和服务费用
    if (page.oType == page.OType.Add || page.oType == page.OType.Edit) {

        console.log(page.oType); //新增 修改 查看 工作流
        var dgrid1 = $NG.getCmpApi('p_form_equipment_list_impl');
        var dgrid2 = $NG.getCmpApi('p_form_equipment_list_svc');


        useValuesChange(({ args }) => {
            console.log(args[0]);
            dgrid1.clearRows();
            dgrid2.clearRows();
            if (dgrid1) {
                $NG.execServer('get_impl_cost_budget_info', {
                    phid_pc: mstform.getItem('phid_pc').getValue()
                }, function (res) {
                    const data = JSON.parse(res.data);
                    console.log(res.data);
                    //默认增行,批量新增表体数据
                    var gridArr = []; //定义表体数组
                    var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                    for (var i = 0; i < gridCount; i++) {
                        var gridObj = {
                        };
                        //对表体字段进行赋值,可以取数据库中的值进行赋值
                        gridObj.u_bill_no = data[i].extendObjects.bill_no;
                        gridObj.u_total_impl_amt = data[i].extendObjects.u_total_impl_labor_amt;
                        gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                        gridObj.u_total_sec_dev_amt = data[i].extendObjects.u_total_sec_dev_amt;
                        gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                        gridArr.push(gridObj);
                    }
                    //调用新增表体行数据的函数
                    dgrid1.addRows(gridArr);
                })
            }
            if (dgrid2) {
                $NG.execServer('get_svc_cost_budget_info', {
                    phid_pc: mstform.getItem('phid_pc').getValue()
                }, function (res) {
                    const data = JSON.parse(res.data);
                    console.log(res.data);
                    //默认增行,批量新增表体数据
                    var gridArr = []; //定义表体数组
                    var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                    for (var i = 0; i < gridCount; i++) {
                        //对表体字段进行赋值,可以取数据库中的值进行赋值
                        var gridObj = {
                        };
                        gridObj.u_bill_no = data[i].extendObjects.bill_no;
                        gridObj.u_total_svc_amt = data[i].extendObjects.u_total_svc_amt;
                        gridObj.u_total_svc_labor_amt = data[i].extendObjects.u_total_svc_labor_amt;
                        gridObj.u_total_daily_amt = data[i].extendObjects.u_total_daily_amt;
                        // gridObj.u_invoice_type = data[i].extendObjects.u_invoice_type;
                        gridArr.push(gridObj);
                    }
                    //调用新增表体行数据的函数
                    dgrid2.addRows(gridArr);
                })
            }
        }, "p_form_equipment_list.u_cnt_no");
    }




    //function
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    function caculatedgrid() {
        console.log('caculatedgrid begin')
        let sum_cost_vat = 0;
        let sum_cost = 0;
        let sum_cnt_amt_vat = 0
        let sum_sub_cost_vat = 0
        let sum_sub_cost = 0
        let sum_pur_cost_vat = 0
        let sum_pur_cost = 0
        let sum_self_cost_vat = 0
        let sum_self_cost = 0
        let sum_impl_cost_vat = 0
        let sum_svc_cost_vat = 0
        let u_total_cnt_amt_vat = mstform.getItem('u_total_cnt_amt_vat').getValue()//合同总额
        let u_win_bid_svc_amt = mstform.getItem('u_win_bid_svc_amt').getValue()//中标服务费

        const DRows = $NG.getCmpApi('p_form_equipment_list_d').getRows();//设备清单页签
        const implRows = $NG.getCmpApi('p_form_equipment_list_impl').getRows();//实施费页签
        const svcRows = $NG.getCmpApi('p_form_equipment_list_svc').getRows();//服务费页签
        DRows.forEach(items => {
            sum_cnt_amt_vat += parseFloat(items.u_cnt_amt_vat) || 0;//合同现额
            sum_sub_cost_vat += parseFloat(items.u_sub_cost_vat) || 0; // 拟分包成本含税
            sum_sub_cost += parseFloat(items.u_sub_cost) || 0; // 拟分包成本未税
            sum_pur_cost_vat += parseFloat(items.u_pur_cost_vat) || 0; // 拟采购成本含税
            sum_pur_cost += parseFloat(items.u_pur_cost) || 0; // 拟采购成本未税
            sum_self_cost_vat += parseFloat(items.u_self_cost_vat) || 0; //拟自制成本含税
            sum_self_cost += parseFloat(items.u_self_cost) || 0;//拟自制成本未税
        });
        implRows.forEach((items) => {
            sum_impl_cost_vat += parseFloat(items.u_total_impl_amt);
        });
        svcRows.forEach((items) => {
            sum_svc_cost_vat += parseFloat(items.u_total_svc_amt);
        });

        sum_cost_vat = sum_sub_cost_vat + sum_pur_cost_vat + sum_self_cost_vat + sum_impl_cost_vat + sum_svc_cost_vat;
        sum_cost = sum_sub_cost + sum_pur_cost + sum_self_cost;

        $NG.updateState((updater) => {
            updater.data.p_form_equipment_list.setProps({
                u_cnt_amt_vat: sum_cnt_amt_vat,//合同现额
                u_sub_cost: sum_sub_cost_vat,//拟分包含税
                u_sub_cost_amt: sum_sub_cost,//拟分包不含税
                u_pur_cost_vat: sum_pur_cost_vat,//拟采购成本含税
                u_pur_cost_amt: sum_pur_cost,//拟采购成本未税
                u_self_cost_vat: sum_self_cost_vat,//拟自制成本含税
                u_self_cost: sum_self_cost,//拟自制成本未税
                u_implement_amt: sum_impl_cost_vat,//实施费
                u_svc_cost_amt: sum_svc_cost_vat,//服务费

                u_total_cost_amt_vat: sum_cost_vat,//总成本含税
                u_total_cost_amt: sum_cost,//总成本不含税
                u_revenue_cost_gm: u_total_cnt_amt_vat - sum_cost_vat,//收入成本毛利
                u_signed_gm_rate: (u_total_cnt_amt_vat - sum_cost_vat) / u_total_cnt_amt_vat,//签单毛利率
                u_svc_amt_rate: u_win_bid_svc_amt / u_total_cnt_amt_vat,//服务费率
                u_bid_gm_rate: (u_total_cnt_amt_vat - sum_cost_vat - u_win_bid_svc_amt) / u_total_cnt_amt_vat,//投标毛利率

                u_sub_cost_ratio: sum_sub_cost_vat / sum_cost_vat,//拟分包成本占比
                u_pur_cost_ratio: sum_pur_cost_vat / sum_cost_vat,//拟采购成本占比
                u_self_cost_ratio: sum_self_cost_vat / sum_cost_vat,//拟自制成本占比
                u_implement_cost_ratio: sum_impl_cost_vat / sum_cost_vat,//实施费占比
                u_svc_cost_ratio: sum_svc_cost_vat / sum_cost_vat,//服务费占比
            })
        });
        console.log('u_total_cost_amt_vat:' + mstform.getItem('u_total_cost_amt_vat').getValue());
        console.log('caculatedgrid end')
    }
    function insertClick() {
        var dgrid = $NG.getCmpApi("p_form_equipment_list_d");
        var orirow = dgrid.getCheckedIndexes()[0] !== undefined
            ? dgrid.getCheckedIndexes()[0]
            : dgrid.getAllData().table.newRow.length;
        var maxrow = dgrid.getAllData().table.newRow.length;
        console.log(orirow);
        dgrid.addRows();
        setTimeout(function () {
            console.log(maxrow);
            dgrid.moveRow(maxrow, orirow + 1);
        }, 100);  // 延迟 100 毫秒，视具体情况可以调整这个值
    }



    function getCntMInfoByPhid(params) {
        $NG.execServer('getCntMInfoByPhid', { phid: mstform.getItem('u_cnt_no').getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(datas);
            //帮助字段赋值
            $NG.updateState((updater) => {
                //【注意这里的表名不能为控件ID，必须要是表名】
                updater.data.p_form_equipment_list.setProps({
                    u_cnt_name: datas.pcm_name,
                    u_total_cnt_amt_vat: datas.cnt_sum_vat_fc,
                    u_cnt_amt_vat: datas.cnt_sum_vat_fc,
                    u_product_line: {
                        value: datas.midwife_phid,
                        label: datas.midwife_name,
                    },
                    u_cnt_type: {
                        value: datas.pct_id,
                        label: datas.pct_name,
                    },
                    u_customer: {
                        value: datas.customer_id,
                        label: datas.customer_name,
                    },
                    u_invoice_type: {
                        value: datas.invoice_type_phid,
                        label: datas.invoice_type_name,

                    }
                });
            });

        });
    }
    function getCntDInfoByPhid(record) {
        $NG.execServer("getCntDInfoByPhid", { cnd_id: mstform.getItem('u_cnt_no').getValue(), phid: record.u_cnt_item }, function (res) {
            if (res.count > 0) {
                var data = JSON.parse(res.data)[0].extendObjects; //单返回值
                record.u_cnt_item_no = data.item_no;//合同清单编码
                record.u_model = data.user_ggxh;//规格型号
                record.u_msunit = data.unit_phid//计量单位
                record.u_msunit_EXName = data.unit_name//计量单位
                record.u_cnt_prc_vat=data.prc_vat_fc,
                record.u_cnt_prc=data.prc_fc,
                record.u_cnt_amt_vat=data.amt_vat_fc,
                record.u_cnt_amt=data.amt_fc
            } else {
                console.log(record.u_cnt_item + '没有找到合同清单')
            }
            dgrid.refreshView()
        });
    }
    function getCntDInfoByNo(record) {
        if (mstform.getItem('u_cnt_no').getValue() && record.u_cnt_item_no) {
            $NG.execServer("getCntDInfoByNo", { cnd_id: mstform.getItem('u_cnt_no').getValue(), item_no: "'" + record.u_cnt_item_no + "'" }, function (res) {
                if (res.count > 0) {
                    var data = JSON.parse(res.data)[0].extendObjects; //单返回值

                    record.u_cnt_item = data.phid//合同清单ID
                    record.u_cnt_item_EXName = data.item_name//合同清单名称
                    record.u_model = data.user_ggxh;//规格型号
                    u_msunit = data.unit_phid//计量单位
                    u_msunit_EXName = data.unit_name//计量单位
                } else {
                    console.log('没有找到合同清单')
                    record.u_cnt_item = null;
                    record.u_cnt_item_EXName = null;
                }
                dgrid.refreshView()
            });
        }
    }

    function getPtInfoByPhid() {
        if (mstform.getItem('phid_pc').getValue()) {
            $NG.execServer('getPtInfoByPhid', { phid: mstform.getItem('phid_pc').getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    //【注意这里的表名不能为控件ID，必须要是表名】
                    updater.data.p_form_equipment_list.setProps({
                        u_sqgw: {//售前顾问
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        u_project_manager: {//项目经理
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        u_division: {//事业部
                            value: datas.phid_org_phid,
                            label: datas.phid_org_name,
                        },
                        u_regional_center: {//区域中心
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        }
                    });
                });

            });
        }
    }

    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_equipment_list.u_cnt_no.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue() && {
                    clientSqlFilter: {
                        bill_type: 1,
                        phid_pc: $NG.getCmpApi('p_form_equipment_list').getItem('phid_pc').getValue()
                    }
                }),
            });
        });
    }

    function cntDFilter() {
        $NG.updateUI(updater => updater.editGrid.p_form_equipment_list_d.u_cnt_item.setProps((p) => {
            return {
                ...p, editor: {
                    ...p.editor,
                    clientSqlFilter: { pphid: $NG.getCmpApi('p_form_equipment_list').getItem('u_cnt_no').getValue() || 0 },
                }
            };
        }));
    }

});